package com.example.shop.cart

import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.example.base.entity.CarEntity
import com.example.base.mvvm.BaseFragment
import com.example.shop.R
import com.example.shop.adapter.CartAdapter
import com.example.shop.databinding.FragmentCartBinding
import com.example.shop.db.AppDb
import com.example.shop.db.AppDbUtils
import com.example.shop.pay.PayActivity


class CartFragment : BaseFragment<FragmentCartBinding,CartViewModel>() {
    val list = mutableListOf<CarEntity>()
    lateinit var cartAdapter: CartAdapter

    override fun initView() {
        cartAdapter = CartAdapter(list)
        binding.cartRv.adapter = cartAdapter
        binding.cartRv.layoutManager = LinearLayoutManager(context)
        viewModel.selectCar()
        total()
        binding.selectAll.setOnCheckedChangeListener { buttonView, isChecked ->
            binding.selectAll.setOnClickListener {
                //更新每一个item中的ischeck的值
                list.forEach {
                    it.isChecked = isChecked
                }
                cartAdapter.notifyDataSetChanged()
                //全选按钮发生变化，金额也要发生变化
                total()
            }
        }

        //点击结算按钮
        binding.toPay.setOnClickListener {
            val checklist = mutableListOf<Boolean>()
            val ids = StringBuffer()
            list.forEach {
                checklist.add(it.isChecked)
            }
            if(true in checklist){
                //存在选中的item，可以去进行支付的操作
                list.forEach {
                    if(it.isChecked){
                        it.orderStatus = 0//待结算状态
                        //保存到数据库中，方便后续支付界面进行展示
                        AppDbUtils.getAppDb().getOrderDao().insertOrder(it)
                        if(ids.length>0){
                            ids.append(",")
                        }
                        ids.append(it.id)
                    }
                }
                viewModel.deleteCar(ids.toString())//删除所有要支付的购车明细
                //跳转到支付界面，同时支付完成后，要刷新当前界面
                val intent = Intent(context,PayActivity::class.java)
                startActivityForResult(intent,200)
            }else{
                ToastUtils.showLong("至少选择一个商品去结算")
            }
        }

        //item子控件上的点击事件
        cartAdapter.addChildClickViewIds(R.id.cart_delete,R.id.cart_add,R.id.cart_sub,R.id.cb)
        cartAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.cart_delete->{
                    viewModel.deleteCar(list[position].id.toString())
                    list.removeAt(position)
                    //只刷新当前item,不影响其他的
                    cartAdapter.notifyItemRemoved(position)
                }
                R.id.cart_add->{
                    viewModel.addCar(list[position].goods_id,1)
                    list[position].count+=1//页面中的数量进行加1操作 ---list集合中的数量也要进行加1
                    ((cartAdapter.getViewByPosition(position,R.id.cart_num)) as TextView).text = "${list[position].count}"
                }
                R.id.cart_sub->{
                    if(list[position].count==1){
                        ToastUtils.showLong("当前商品不能再减少了")
                    }else{
                        //购物车数量减少一个，相当增加了一个-1
                        viewModel.addCar(list[position].goods_id,-1)
                        list[position].count-=1//页面中的数量进行减1操作 ---list集合中的数量也要进行减1
                        ((cartAdapter.getViewByPosition(position,R.id.cart_num)) as TextView).text = "${list[position].count}"
                    }
                }
                R.id.cb->{
                    list[position].isChecked = !list[position].isChecked
                    (cartAdapter.getViewByPosition(position,R.id.cb) as CheckBox).isChecked = list[position].isChecked
                }
            }
            //无论item发生了任何修改，合计金额都需要变化
            total()
            checkAll()//检查全选的值

        }

    }

    private fun checkAll() {
        val checklist = mutableListOf<Boolean>()
        list.forEach {
            checklist.add(it.isChecked)
        }
        binding.selectAll.isChecked = false !in checklist
    }

    private fun total() {
        var money = 0
        list.forEach {
            if(it.isChecked){
                money+=it.goods_default_price*it.count
            }
        }
        binding.totalMoney.text = "合计：${money} 元"
    }

    override fun initData() {

        viewModel.success.observe(this){
            if(it.code==200){
                list.clear()
                list.addAll(it.data)
                cartAdapter.notifyDataSetChanged()
                checkAll()
                total()
            }else{
                ToastUtils.showLong(it.message)
            }
        }
        viewModel.deleteSuccess.observe(this){
            ToastUtils.showLong(it.message)
        }
        viewModel.addSuccess.observe(this){
            ToastUtils.showLong(it.message)
        }
    }

    override fun getViewModel(): Class<CartViewModel>  = CartViewModel::class.java

    override fun getLayout(): Int = R.layout.fragment_cart
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==200&&resultCode==201){
            viewModel.selectCar()
        }
    }

}